const userDao = require('../dao/userDao')
const md5 = require('md5')
const jwt = require('jsonwebtoken')
const config = require('../config/config.js')

// 用户注册
exports.register = async ctx => {
  let body = ctx.request.body
  const isRegister = await userDao.findByName(body);
  if (isRegister) {
    ctx.body = {
      code: 1,
      message: '该账号已被注册'
    }
    return
  }
  body.password = md5(body.password)
  const res = await userDao.create(body);
  ctx.body = {
    code: 0,
    message: '注册成功'
  }
}

// 用户登录
exports.login = async ctx => {
  let body = ctx.request.body
  console.log(body)
  let res = await userDao.findByName(body);
  if(!res){
    ctx.body = {
      code: 1,
      message: '账号或密码错误',
    }
    return 
  }
  let { id,username,password} = res
  if (body.username === username && md5(body.password) === password) {
    let {
      secretKey,
      expiresIn
    } = config.security
    let payload = {
      id: id,
      username: username
    }
    let token = jwt.sign(payload, secretKey, {
      expiresIn: expiresIn
    });
    ctx.body = {
      code: 0,
      message: '登录成功',
      token
    }
  } else {
    ctx.body = {
      code: 1,
      message: '账号或密码错误',
    }
  }
}

// 获取个人信息
exports.getUserInfo = async ctx => {
  let token = ctx.request.headers["authorization"];
  let payload = jwt.verify(token,config.security.secretKey)
  const userInfo = await userDao.findById(payload);
  ctx.body = {
    code:0,
    data:userInfo
  }
}

// 修改用户信息
exports.ediUserInfo = async ctx => {
  let body = ctx.request.body
  const res = await userDao.update(body);
  ctx.body = {
    code: 0,
    data:res
  }
}

// 获取所有用户信息
exports.getAllUser = async ctx => {
  let { p = 1,limit = 10 } = ctx.request.query
  let offset = (p - 1) * limit;
  let body = {
    offset:offset,
    limit:Number(limit)
  }
  const res = await userDao.findAll(body);
  ctx.body = {
    code: 0,
    data: res
  }
}

// 根据用户名 真实名搜索用户
exports.searchUser = async ctx => {
  let {searchQuery} = ctx.request.query
  console.log(searchQuery,'=====')
  let res = await userDao.getUserByName(searchQuery)
  ctx.body = {
    code:0,
    data:res
  }
}

// 获取所有用户信息
exports.getAllUser = async ctx => {
  let { p = 1,limit = 10 } = ctx.request.query
  let offset = (p - 1) * limit;
  let body = {
    offset:offset,
    limit:Number(limit)
  }
  const res = await userDao.findAll(body);
  ctx.body = {
    code: 0,
    data: res
  }
}